package gruppoSoluzione.mainService.services;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class ScriviTxtComeHtml {
	
	private DataOutputStream out;
	private FileInputStream requestedFileStream;
	private String fileName;
	
	public ScriviTxtComeHtml(DataOutputStream out, FileInputStream requestedFileStream, String fileName) throws IOException {
		this.out = out;
		this.requestedFileStream = requestedFileStream;
		this.fileName = fileName;
		write();
	}
	
	public void write() throws IOException {
		//header del file txt: settaggio del css
		out.writeBytes(	"<html>\n"+ 
						"	<head>\n"+ 
						"		<title> " + fileName + " </title>\n"+ 
						"		<meta charset='UTF-8' />\n"+ 
						"		<link rel='stylesheet' type='text/css' href='txt.css'/>\n"+ 
						"	</head>\n"+ 
						"	\n");
		
		//corpo del file txt: legge il file e lo stampa un byte alla volta, con l'opportuna formattazione
		out.writeBytes("\t<body>\n");
		out.writeBytes("\t\t<p> ");
		int fileByte = 0;
		while (fileByte != -1) {
		    fileByte = requestedFileStream.read();
		    if (fileByte == (int)(char)"\n".charAt(0)) {
		    	out.writeBytes(" </p>\n\t\t<p> ");
			}else if(fileByte != -1){
				out.write(fileByte);
			}
		}
		out.writeBytes(" </p>\n");
		out.writeBytes("\t</body>\n");
		out.writeBytes("</html>\n");
	}
}
